<template>
  <view class="login-container">
    <!-- 标题 -->
    <view class="login-title">欢迎回来</view>
    <view class="login-subtitle">请登录您的账号</view>
    
    <!-- 账号输入 -->
    <view class="input-group">
      <input 
        v-model="username" 
        placeholder="请输入手机号/用户名" 
        class="input-box"
        :class="{'input-error': errors.username}"
      />
      <view v-if="errors.username" class="error-message">{{ errors.username }}</view>
    </view>
    
    <!-- 密码输入 -->
    <view class="input-group">
      <input 
        v-model="password" 
        placeholder="请输入密码" 
        type="password"
        class="input-box"
        :class="{'input-error': errors.password}"
        @keyup.enter="handleLogin"
      />
      <view v-if="errors.password" class="error-message">{{ errors.password }}</view>
    </view>
    
    <!-- 记住密码和忘记密码 -->
    <view class="login-options">
      <label class="remember-me">
        <checkbox-group @change="toggleRemember">
          <checkbox :checked="rememberMe" color="#3a7afe" />
        </checkbox-group>
        <text>记住密码</text>
      </label>
      <view class="forgot-password" @click="goToForgotPassword">忘记密码?</view>
    </view>
    
    <!-- 登录按钮 -->
    <button 
      @click="handleLogin"
      class="login-btn"
      :disabled="loading"
      :style="{opacity: loading ? 0.7 : 1}"
    >
      {{ loading ? '登录中...' : '登录' }}
    </button>
    
    <!-- 注册链接 -->
    <view class="register-link">
      还没有账号? <text class="register-text" @click="goToRegister">立即注册</text>
    </view>
    
    <!-- 状态提示 -->
    <view v-if="message" class="message" :class="messageType">
      {{ message }}
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'

const username = ref('')
const password = ref('')
const loading = ref(false)
const message = ref('')
const messageType = ref('') // 'success' 或 'error'
const rememberMe = ref(false)
const errors = ref({
  username: '',
  password: ''
})

onMounted(() => {
  // 从本地存储加载记住的账号密码
  const savedUser = uni.getStorageSync('rememberedUser')
  if (savedUser) {
    username.value = savedUser.username
    password.value = savedUser.password
    rememberMe.value = true
  }
})

const validateForm = () => {
  let isValid = true
  errors.value = { username: '', password: '' }
  
  if (!username.value.trim()) {
    errors.value.username = '请输入账号'
    isValid = false
  }
  
  if (!password.value) {
    errors.value.password = '请输入密码'
    isValid = false
  } else if (password.value.length < 6) {
    errors.value.password = '密码长度不能少于6位'
    isValid = false
  }
  
  return isValid
}

const handleLogin = () => {
  if (!validateForm()) return

  loading.value = true
  message.value = ''

  uni.request({
    url: 'http://192.168.153.1:8080/users/login',
    method: 'POST',
    data: {
      username: username.value,
      password: password.value
    },
    success: (res) => {
      console.log('登录响应数据:', JSON.stringify(res.data, null, 2))
      
      if (res.data.code === 200200) {
        // 根据实际响应数据获取userId（您的接口返回的是userId字段）
        const userId = res.data.data.users.u_id
        
        if (!userId) {
          console.error('用户ID未定义，完整响应:', res.data)
          showMessage('登录成功但获取用户信息失败', 'error')
          return
        }

        showMessage(res.data.message || '登录成功', 'success')
        
        // 存储用户信息（前端统一使用U_Id字段）
        const userInfo = {
          username: username.value,
          U_Id: userId,  // 将接口返回的userId存储为U_Id
          loginTime: new Date().toISOString()
        }
        console.log(userId)
        uni.setStorageSync('userInfo', userInfo)

        // 记住密码处理
        if (rememberMe.value) {
          uni.setStorageSync('rememberedUser', {
            username: username.value,
            password: password.value
          })
        } else {
          uni.removeStorageSync('rememberedUser')
        }

        // 登录成功跳转
        setTimeout(() => {
          uni.switchTab({
            url: '/pages/index/index'
          })
        }, 1500)
      } else {
        showMessage(res.data.message || '登录失败，请检查账号密码', 'error')
      }
    },
    fail: (err) => {
      console.error('登录请求失败:', err)
      showMessage('网络连接异常，请检查后重试', 'error')
    },
    complete: () => {
      loading.value = false
    }
  })
}

const toggleRemember = (e) => {
  rememberMe.value = e.detail.value.length > 0
}

const goToRegister = () => {
  uni.navigateTo({
    url: '/pages/register/register'
  })
}

const goToForgotPassword = () => {
  uni.navigateTo({
    url: '/pages/forget/forget'
  })
}

const showMessage = (msg, type) => {
  message.value = msg
  messageType.value = type
  // 3秒后自动消失
  setTimeout(() => {
    message.value = ''
  }, 3000)
}
</script>

<style>
.login-container {
  padding: 40rpx 60rpx;
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f8f8f8;
}

.login-title {
  font-size: 48rpx;
  font-weight: bold;
  text-align: center;
  margin: 80rpx 0 20rpx;
  color: #333;
}

.login-subtitle {
  font-size: 28rpx;
  text-align: center;
  margin-bottom: 80rpx;
  color: #999;
}

.input-group {
  margin-bottom: 40rpx;
}

.input-box {
  height: 100rpx;
  border: 1rpx solid #e6e6e6;
  border-radius: 12rpx;
  padding: 0 30rpx;
  font-size: 30rpx;
  width: 100%;
  box-sizing: border-box;
  background-color: #fff;
}

.input-box:focus {
  border-color: #3a7afe;
}

.input-error {
  border-color: #f56c6c;
}

.error-message {
  color: #f56c6c;
  font-size: 24rpx;
  margin-top: 10rpx;
  padding-left: 10rpx;
}

.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40rpx;
  font-size: 26rpx;
  color: #666;
}

.remember-me {
  display: flex;
  align-items: center;
}

.forgot-password {
  color: #3a7afe;
}

.login-btn {
  height: 100rpx;
  line-height: 100rpx;
  background-color: #3a7afe;
  color: white;
  border-radius: 12rpx;
  font-size: 34rpx;
  margin: 40rpx 0;
  border: none;
}

.login-btn:active {
  opacity: 0.8;
}

.register-link {
  text-align: center;
  font-size: 28rpx;
  color: #999;
  margin-top: 20rpx;
}

.register-text {
  color: #3a7afe;
  margin-left: 10rpx;
}

.message {
  margin-top: 30rpx;
  padding: 20rpx;
  border-radius: 8rpx;
  text-align: center;
  font-size: 28rpx;
}

.message.success {
  background-color: #f0f9eb;
  color: #67c23a;
}

.message.error {
  background-color: #fef0f0;
  color: #f56c6c;
}
</style>